package com.example.dianproject.repository;

import com.example.dianproject.entity.MeterReading;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.util.List;

@Repository
public interface MeterReadingRepository extends JpaRepository<MeterReading, Long> {
    List<MeterReading> findByMeterIdOrderByReadingDateDesc(Long meterId);
    
    List<MeterReading> findByReadingDateBetweenOrderByReadingDateDesc(LocalDate startDate, LocalDate endDate);
    
    MeterReading findFirstByMeterIdOrderByReadingDateDesc(Long meterId);

    List<MeterReading> findByMeterIdAndReadingDateAfterOrderByReadingDateAsc(Long meterId, LocalDate readingDate);

    Long countByReadingDateBetween(LocalDate startDate, LocalDate endDate);

    @Query("SELECT mr FROM MeterReading mr LEFT JOIN FETCH mr.meter m LEFT JOIN FETCH m.customer ORDER BY mr.readingDate DESC, mr.createdTime DESC")
    List<MeterReading> findAllWithMeterAndCustomer();

    @Query(value = "SELECT DISTINCT mr FROM MeterReading mr LEFT JOIN FETCH mr.meter m LEFT JOIN FETCH m.customer ORDER BY mr.readingDate DESC, mr.createdTime DESC")
    List<MeterReading> findRecentReadings(Pageable pageable);
} 